<?php


namespace app\api\controller\xilujob;


use addons\xilujob\controller\WeixinMini;
use app\common\controller\xilujob\XilujobApi;
use app\common\library\xilujob\ResumeLibrary;
use app\common\model\xilujob\Chat;
use app\common\model\xilujob\ChatSession;
use app\common\model\xilujob\CompanyProfile;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Inform;
use app\common\model\xilujob\JobApply;
use app\common\model\xilujob\JobCall;
use app\common\model\xilujob\JobViewLog;
use app\common\model\xilujob\UserCollection;
use think\db\Query;
use think\Exception;
use function fast\array_get;

class Job extends XilujobApi
{
    protected $noNeedLogin = ['recommend_jobs','lists','detail','similar_jobs'];
    protected $noNeedRight = ['*'];
    protected $restrictedActions = ['*'];

    /**
     * @ApiTitle (推荐工作)
     * @ApiSummary (热门工作推荐, 首页及个人用户在个人中心的推荐)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job/recommend_jobs)
     * @ApiHeaders (name=cityid, type=int, required=true, description="城市id")
     * @ApiParams (name="page", type="int", description="页码")
     * @ApiParams (name="pagesize", type="int", description="每页数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="array", sample="['jobs':[{}],'total':125]", description="扩展数据返回")
     */
    public function recommend_jobs() {
        $user = $this->auth->getUser();
        $params = $this->request->param();
        $params['city_id'] = $this->cityId;
        $jobs = \app\common\model\xilujob\Job::recommendJobs($user, $params);
        $this->success('查询成功', ['jobs'=>$jobs['jobs'],'total'=>$jobs['total']]);
    }


    /**
     * @ApiTitle (职位列表)
     * @ApiSummary (全部职位、搜索等)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job/recommend_jobs)
     * @ApiHeaders (name=cityid, type=int, required=true, description="城市id")
     * @ApiParams (name="cate_type", type="int", decription="首页中间分类(labour:蓝领,parttime:兼职职位,redpacket:红包,brand:名企大厂)")
     * @ApiParams (name="district_id", type="int", decription="地区id")
     * @ApiParams (name="town_id", type="int", description="城镇id")
     * @ApiParams (name="distance", type="int", description="距离")
     * @ApiParams (name="category_id", type="int", description="行业id")
     * @ApiParams (name="salary_type", type="int", description="薪资类型")
     * @ApiParams (name="salary_min", type="int", description="薪资下限")
     * @ApiParams (name="salary_max", type="int", description="薪资上限")
     * @ApiParams (name="scale_id", type="int", description="公司规模")
     * @ApiParams (name="work_experience_id", type="int", description="工作年限")
     * @ApiParams (name="type", type="int", description="职位性质(1:全职,2:兼职)")
     * @ApiParams (name="education_level_id", type="int", description="学历")
     * @ApiParams (name="benefit_id", type="int", description="福利")
     * @ApiParams (name="refresh_days", type="int", description="更新时间")
     * @ApiParams (name="q", type="string", description="搜索关键词")
     * @ApiParams (name="pagesize", type="int", description="每页数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="array", sample="['jobs':[{}],'total':125]", description="扩展数据返回")
     */
    public function lists() {
        $params = $this->request->param();
        $params['city_id'] = $this->cityId;
        if(isset($params['benefit_id'])) {
            //格式化为id数组
            $params['benefit_id'] = json_decode($params['benefit_id'],true) ? : [];
        }
        $jobs = \app\common\model\xilujob\Job::searchJobs($params);
        $this->success('查询成功',$jobs);
    }

    /**
     * @ApiTitle (职位详情)
     * @ApiSummary (职位详情)
     * @ApiMethod (POST)
     * @ApiRoute ('/api/xilujob.job/detail')
     * @ApiParams (name="job_id", type="int", require=true, description="职位id")
     */
    public function detail() {
        $jobId = $this->request->param('job_id');
        $job = \app\common\model\xilujob\Job::with([
            'job_info',
            'job_category',
            'locations'=>function($query){$query->with(['province','city','district']);},
            'user'=>function(Query $query){$query->withField('id,avatar,nickname');},
            'city'=>function(Query $query){$query->withField('id,name');},
            'district'=>function(Query $query){$query->withField('id,name');},
            'work_experience'=>function(Query $query){$query->withField('id,name');},
            'education_level'=>function(Query $query){$query->withField('id,name');},
            'benefits'=>function(Query $query){$query->withField('id,name');},
            'enterpriseinfo'=>function(Query $query){$query->withField('id,company_name,full_name,environment_images,lng,lat,address,logo');}
        ])->find($jobId);
        if(!$job || $job->status!=\app\common\model\xilujob\Job::STATUS_ENABLED) {
            $this->error(__('no record'));
        }
        if(get_addon_config('xilujob')['hide_contact']) {
            $job->job_info->contact_phone = substr($job->job_info->contact_phone,0,3).'********';
        }
        JobViewLog::viewJob($this->auth->id, $jobId);
        $isFav = UserCollection::isFav($this->auth->id, $jobId, UserCollection::TYPE_JOB);
        $isApplying = JobApply::isApplying($this->auth->id, $jobId);
        $user = null;
        if($this->auth->isLogin()){
            $user = $this->auth->getUser();
            $user = ['nickname'=>$user->nickname,'mobile'=>$user->mobile];
        }
        $this->success('查询成功',['job'=>$job,'is_fav'=>$isFav, 'is_applying'=>$isApplying,
            'user'=>$user]);
    }

    /**
     * @ApiTitle (相似职位)
     * @ApiSummary (相似职位推荐)
     * @ApiMethod (POST)
     * @ApiRoute (/api/job/similar_jobs)
     * @ApiHeaders (name=token,type=string,description="Token")
     * @ApiHeaders (name=cityid,type=int,description="城市id")
     * @ApiParams (name="job_id",type="int", decription="职位id")
     */
    public function similar_jobs() {
        $jobId = $this->request->param('job_id');
        $job = \app\common\model\xilujob\Job::with(['job_category'])->find($jobId);
        if(!$job) {
            $this->error('职位已被删除');
        }
        $jobs = \app\common\model\xilujob\Job::getSimilarJobs($jobId);
        $this->success('查询成功',$jobs);
    }

    /**
     * @ApiTitile (投递简历)
     * @ApiSummary (用户主动投递简历)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job/apply)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiHeaders (name=cityid,type=int,description="城市id")
     * @ApiParams (name=job_id, type=int, require=true, description="职位id")
     */
    public function apply() {
        $job_id = $this->request->post('job_id');
        $resume = \app\common\model\xilujob\Resume::getUserResume($this->auth->id);
        if(!$resume) {
            // 进入个人中心即创建一份简历
            $resume = ResumeLibrary::createResume($this->auth->getUser());
            $resume = \app\common\model\xilujob\Resume::getResume($resume->id);
        }
        try {
            $ret = JobApply::applyJob($this->auth->id, $job_id);
        }catch (Exception $e){
            $this->error($e->getMessage(),'',$e->getCode());
        }
        $this->success('投递成功',$ret);
    }

    /**
     * @ApiTitile (收藏&取消收藏)
     * @ApiSummary (收藏&取消收藏)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job/toggle_fav)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=job_id, type=int, require=true, description="职位id")
     */
    public function toggle_fav() {
        $jobId = $this->request->post('job_id');
        $result = UserCollection::toggleFav($this->auth->id, $jobId, UserCollection::TYPE_JOB);
        $this->success('操作成功',['is_fav'=>$result]);
    }


    /**
     * @ApiTitile (收藏列表)
     * @ApiSummary (收藏列表)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job/fav_list)
     */
    public function fav_list() {
        $jobs = \app\common\model\xilujob\Job::field('id,publisher_id,type,job_name,job_category_id,city_id,district_id,town_id,in_hurry,direct,shop,red_packet,red_packet_instruction,work_experience_id,education_level_id,salary_type,salary_min,salary_max,refresh_date')
            ->with([
                'city'=>function(Query $query){$query->withField('id,name,shortname');},
                'district'=>function(Query $query){$query->withField('id,name,shortname');},
                'town'=>function($query){$query->withField('id,name,shortname');},
                'work_experience'=>function(Query $query){$query->withField('id,name');},
                'education_level'=>function(Query $query){$query->withField('id,name');},
                'benefits'=>function(Query $query){$query->withField('id,name');},
                'enterpriseinfo'=>function(Query $query){$query->withField('id,company_name,full_name');}
            ])
            ->join('xilujob_user_collection c', 'job.id=c.collection_id')
            ->where('c.collection_type', UserCollection::TYPE_JOB)
            ->where('c.user_id', $this->auth->id)
            ->order('c.id','desc')
            ->paginate();
        $this->success('查询成功',$jobs);
    }


    /**
     * @ApiTitile (我看过的记录)
     * @ApiSummary (我看过的记录)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job/my_look)
     */
    public function my_look() {
        $paginator = \app\common\model\xilujob\Job::with([
            'city'=>function(Query $query){$query->withField('id,name');},
            'district'=>function(Query $query){$query->withField('id,name');},
            'town'=>function($query){$query->withField('id,name,shortname');},
            'work_experience'=>function(Query $query){$query->withField('id,name');},
            'education_level'=>function(Query $query){$query->withField('id,name');},
            'benefits'=>function(Query $query){$query->withField('id,name');},
            'enterpriseinfo'=>function(Query $query){$query->withField('id,company_name,full_name');}
        ])->join('xilujob_job_view_log log','job.id=log.job_id')
            ->where('log.user_id', $this->auth->id)
            ->order('log.view_time','desc')
            ->field('job.*, log.view_time')
            ->paginate();
        $this->success('查询成功',$paginator);
    }

    /**
     * @ApiTitle (职位举报)
     * @ApiSummary (职位投诉)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xilujob.job/inform)
     * @ApiHeaders (name=token,type=string,description="Token")
     * @ApiParams  (name=job_id,type=int,description="职位id")
     * @ApiParams  (name=job_inform_type_id,type=int,description="举报类型id")
     * @ApiParams  (name=content, type=int, description="举报内容")
     * @ApiParams  (name=images, type=int, description="举报图片")
     * @ApiParams  (name=contact, type=int, description="联系方式")
     */
    public function inform() {
        $params = $this->request->post();
        $params['user_id'] = $this->auth->id;

        $inform = new Inform();
        $images = array_get($params, 'images', '');
        $params['images'] = is_array($images) ? implode(',', $images) : $images;

        $validate = new \app\common\validate\xilujob\Inform();

        if(!$validate->check($params)){
            $this->error($validate->getError());
        }
        $ret = $inform->save($params);

        if($ret===false) {
            $this->error($inform->getError());
        }
        $this->success('成功',$inform);
    }

    public function job_call() {
        $userId = $this->auth->id;
        $jobId = $this->request->post('job_id');
        try {
            $ret = JobCall::getJobCall($userId, $jobId);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $job = \app\common\model\xilujob\JobInfo::field('id,contact_phone')->where('job_id',$jobId)->find();
        $this->success('', ['phone'=>$job->contact_phone]);

    }


    /**
     * 职位分享海报
     */
    public function poster_info() {
        $id = $this->request->param('job_id');
        $job = \app\common\model\xilujob\Job::get($id);
        if(!$job->miniapp_code) {
            $wx = new WeixinMini();
            $page = "pages/jobs_detail/jobs_detail?id=".$id;
            $res = $wx->getlimited($page);
            if(!$res) $this->error('获取小程序二维码失败');
            $root = '.';
            $path = '/zhaopin/miniapp_job/';
            if (!file_exists($root . $path)) {
                @mkdir($root . $path, 0777, true);
            }
            $filename = $job->id.'.png';
            $qrcode = $path.$filename;
            $alioss = get_addon_info("alioss");
            if($alioss && $alioss['state']==1){
                Common::uploadAlioss($qrcode, $res);
            }else{
                file_put_contents($root.$qrcode,$res);
            }
            $job->save(['miniapp_code'=>cdnurl($qrcode,true)]);
        }
        //$company = CompanyProfile::where('id',$job->publisher_id)->find();
        $img = EnterpriseInfo::where('company_id',$job->publisher_id)->value('logo');
        $this->success('',[
            'text1' => $job->job_name,
            'text2'=>"招{$job->num}人".($job->education_level?'/'.$job->education_level->name:'')
                .($job['type']==1?'/全职':'/兼职').($job->work_experience?'/'.$job->work_experience->name:''),
            'text3' => '', 'text4' => '欢迎投递简历',
            'img2'=>cdnurl($job->miniapp_code,true),
            'img1'=>cdnurl($img,true),
            'tip'=>'长按识别二维码，查看职位详情'
        ]);
    }


    /**
     * 投递申请聊天最新职位
     */
    public function chat_job(){
        $user = $this->auth->getUser();
        $receive_user_id = $this->request->post('receive_user_id');
        $chatSession = ChatSession::checkSession($user->id,$receive_user_id);
        $jobId = Chat::where('session_id',$chatSession->id)->where('job_id','>',0)->order('id','desc')->value('job_id');
        $this->success('',$jobId);
    }

    //已沟通的职位
    public function chat_job_lists(){
        $user = $this->auth->getUser();
        $receive_user_id = $this->request->param('receive_user_id');
        $chatSession = ChatSession::checkSession($user->id,$receive_user_id);
        $jobIds = Chat::where('session_id',$chatSession->id)
            ->where('job_id','>',0)
            ->order('id','desc')
            ->select();
        $this->success('',$jobIds);
    }

}